package com.clj.handler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JOptionPane;

import com.clj.entity.AdminDO_clj;
import com.clj.service.impl.AdminServiceCljImpl_clj;
import com.clj.view.LoginView_clj;
import com.clj.view.MainView_clj;

/**
 * Author: Harry Chen
 * Date: 2023/02/24 15:59
 * Description: 登录按钮的监听器
 */
public class LoginHandler_clj extends KeyAdapter implements ActionListener {
    private LoginView_clj loginViewClj;

    public LoginHandler_clj(LoginView_clj loginViewClj) {
        this.loginViewClj = loginViewClj;
    }

    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("重置".equals(text)) {
            loginViewClj.getUserTxt().setText("");
            loginViewClj.getPwdField().setText("");
        } else if ("登录".equals(text)) {
            login();
        }
    }

    private void login() {
        String user = loginViewClj.getUserTxt().getText();
        char[] chars = loginViewClj.getPwdField().getPassword();
        if (user == null || "".equals(user.trim()) || chars == null) {
            JOptionPane.showMessageDialog(loginViewClj, "用户名密码必填");
            return;
        }
        String pwd = new String(chars);
        System.out.println(user + ":" + pwd);

        AdminServiceCljImpl_clj adminService = new AdminServiceCljImpl_clj();
        AdminDO_clj adminDoClj = new AdminDO_clj();
        adminDoClj.set用户名(user);
        adminDoClj.set密码(pwd);
        boolean flag = adminService.validateAdmin(adminDoClj);
        if (flag) {
            //跳转到主界面并销毁登陆界面
            new MainView_clj();
            loginViewClj.dispose();
        } else {
            JOptionPane.showMessageDialog(loginViewClj, "用户名密码错误");
        }
    }

    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }
}
